package com.czn.bookshop.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czn.bookshop.entity.Cart;
import com.czn.bookshop.entity.CartInfo;
import com.czn.bookshop.entity.CartVo;
import com.czn.bookshop.mapper.CartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 购物车Service
 *
 * @author ChenZeNan
 * @create 2020-12-29 13:58
 */
@Service
public class CartService extends ServiceImpl<CartMapper, Cart> {
    @Autowired
    private CartMapper cartMapper;

    /**
     * 根据用户查询购物车记录
     *
     * @param userId
     * @return
     */
    public List<CartVo> findCartByUserId(Integer userId) {
        return cartMapper.findCartListByUserId(userId);
    }

    /**
     * 统计当前购物车所有东西的总价格
     *
     * @return
     */
    public double getCartItemTotal(List<CartVo> list) {
        double sum = 0.0;
        for (CartVo cartVo : list) {
            sum += cartVo.getNewPrice() * cartVo.getCount();
        }
        return sum;
    }

    /**
     * 包装购物车数量和价格等信息
     *
     * @param
     * @param
     * @return
     */
    public CartInfo wrapperCartInfo(List<CartVo> list) {
        CartInfo cartInfo = new CartInfo();
        cartInfo.setNum(list.size());
        cartInfo.setTotalPrice(getCartItemTotal(list));
        return cartInfo;
    }

    /**
     * 批量删除购物车记录行
     *
     * @param ids
     * @return
     */
    public String batchDelete(String ids) {
        if (ids != null) {
            String[] idArr = ids.split(",");
            cartMapper.deleteBatchIds(Arrays.asList(idArr));
        }
        return "success";
    }

    /**
     * 根据购物车里面所勾选记录的id查询相应记录
     *
     * @param ids
     * @return
     */
    public List<CartVo> findCartByIds(String ids) {
        String[] idArr = ids.split(",");
        return cartMapper.findCartListByIds(Arrays.asList(idArr));
    }
}
